package edu.huhu.dt.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.huhu.dt.dto.UserPageDTO;
import edu.huhu.dt.entity.User;
import edu.huhu.dt.result.PageResult;
import edu.huhu.dt.result.Result;
import edu.huhu.dt.service.IUserService;
import edu.huhu.dt.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sean
 * @since 2023-06-25
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制器")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("分页获取用户列表")
    // DTO设计是去看原型，前端传给后端的参数，都封装到一个XxxDTO类中
    @PostMapping("/pageQuery")
    public Result findUsers(@RequestBody UserPageDTO userPageDTO){
        log.info("[分页获取用户列表] dto:{}",userPageDTO);
        IPage<User> userPage = new Page<>(userPageDTO.getPage(),userPageDTO.getPageSize());
        userService.page(userPage);
        // 实体->VO
        // userPage.getRecords() User类（实体类）
        List<UserVO> voList = new ArrayList<>();
        // stream
        userPage.getRecords().stream().forEach(user -> {
            // DTO->VO
            UserVO userVO =new UserVO();
            BeanUtils.copyProperties(user,userVO);
            voList.add(userVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setRecords(voList);
        pageResult.setTotal(userPage.getTotal());
        return Result.success(pageResult);
    }
}
